package lab.jsp;

import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab.domain.Artist;
import lab.jsp.util.DatabaseHelper;

/**
 *
 * @author Smike
 */
public class EditArtist extends AbstractJSP<Artist> {

    public static final String ID = "id";
    public static final String NAME = "name";
    Artist artist;

    @Override
    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do nothing
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        artist = new Artist();
        String id = request.getParameter(ID);
        if (id != null) {
            artist.setId(Integer.valueOf(id));
        } else {
            artist.setId(-1);
        }
        super.doGet(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        artist = new Artist();
        String id = request.getParameter(ID);
        if (id != null) {
            artist.setId(Integer.valueOf(id));
        } else {
            throw new IllegalArgumentException();
        }
        try {
            if (request.getParameter("save") != null) {
                artist.setName(request.getParameter(NAME));
                if (artist.getId() >= 0) {
                    DatabaseHelper.updateArtist(getConnection(), artist);
                } else {
                    DatabaseHelper.insertArtist(getConnection(), artist);
                }
            } else if (request.getParameter("delete") != null) {
                if (artist.getId() >= 0) {
                    DatabaseHelper.deleteArtist(getConnection(), artist);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(EditArtist.class.getName()).log(Level.SEVERE, null, ex);
        }
        response.sendRedirect("artists.jsp");
    }

    @Override
    protected Artist getData() {
        Logger.getLogger(EditArtist.class.getName()).severe("id is " + artist.getId());
        if (artist.getId() >= 0) {
            try {
                return (Artist) DatabaseHelper.findArtist(getConnection(), artist.getId());
            } catch (SQLException ex) {
                Logger.getLogger(EditArtist.class.getName()).log(Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            }
        } else {
            return artist;
        }
    }
}
